package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableQuotaChangeRecord;

public class TagQuotaChangeRecord {
    public long uid;
    public int last_fix_quota_time;
    public int last_tmp_quota_time;

    public TagQuotaChangeRecord() {}

    public TagQuotaChangeRecord(long uid, int last_fix_quota_time, int last_tmp_quota_time) {
        this.uid = uid;
        this.last_fix_quota_time = last_fix_quota_time;
        this.last_tmp_quota_time = last_tmp_quota_time;
    }

    public static TagQuotaChangeRecord init(long uid) {
        return new TagQuotaChangeRecord(uid, 0, 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableQuotaChangeRecord.QUERYSQL);
        DataStream<Tuple2<Boolean, TableQuotaChangeRecord>> inputStream =
                tableEnv.toRetractStream(tableRes, TableQuotaChangeRecord.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableQuotaChangeRecord>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableQuotaChangeRecord> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagQuotaChangeRecord-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableQuotaChangeRecord>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableQuotaChangeRecord> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableQuotaChangeRecord>, String>() {
                                    ValueState<TagQuotaChangeRecord> quotaChangeRecordVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        quotaChangeRecordVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagQuotaChangeRecord>(
                                                                        "quotaChangeRecordVState",
                                                                        TagQuotaChangeRecord
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableQuotaChangeRecord> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        String action = value.f1.getAction();
                                        int create_time = value.f1.getCreated_at();

                                        TagQuotaChangeRecord tmpState =
                                                quotaChangeRecordVState.value();
                                        TagQuotaChangeRecord curState =
                                                tmpState == null
                                                        ? TagQuotaChangeRecord.init(uid)
                                                        : tmpState;
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("uid", uid);

                                        switch (action) {
                                            case "0004":
                                                if (curState.getLast_fix_quota_time()
                                                        < create_time) {
                                                    curState.last_fix_quota_time = create_time;
                                                    jsonObject.put(
                                                            "last_fix_quota_time", create_time);

                                                    quotaChangeRecordVState.update(curState);
                                                    out.collect(jsonObject.toString());
                                                }
                                                break;
                                            case "0007":
                                                if (curState.getLast_tmp_quota_time()
                                                        < create_time) {
                                                    curState.last_tmp_quota_time = create_time;
                                                    jsonObject.put(
                                                            "last_tmp_quota_time", create_time);

                                                    quotaChangeRecordVState.update(curState);
                                                    out.collect(jsonObject.toString());
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                });
        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getLast_fix_quota_time() {
        return last_fix_quota_time;
    }

    public int getLast_tmp_quota_time() {
        return last_tmp_quota_time;
    }

    @Override
    public String toString() {
        return "TagQuotaChangeRecord{"
                + "uid="
                + uid
                + ", last_fix_quota_time="
                + last_fix_quota_time
                + ", last_tmp_quota_time="
                + last_tmp_quota_time
                + '}';
    }
}
